<?php

namespace api\modules\v1\controllers\member;


use api\controllers\UserAuthController;
use api\modules\v1\forms\WithdrawForm;
use common\models\member\MemberWithdraw as Withdraw;
use common\helpers\ResultHelper;
use common\models\member\CreditsLog;
use common\models\forms\CreditsLogForm;
use Yii;
class WithdrawController extends UserAuthController
{
   
    public $modelClass = Withdraw::class;
    /**
     * 提现
     * type 提现类型 不填 查全部 0 J余额提现  1 D余额提现
     * @return [type] [description]
     */
    public function actionList($day='',$state='',$limit=100, $offset=0,$type=null){
        $member_id = Yii::$app->user->identity->member_id;
        $query = $this->modelClass::find()->where(['member_id'=>$member_id])->select(['type','created_at', 'confirm_at', 'state', 'amount', 'bank_user_name', 'mobile', 'address']);
        if ($day) {
            $time = strtotime($day);
            $query->andWhere(['>=', 'created_at', $time]);
            $query->andWhere(['<', 'created_at', $time + 86400]);
        }
        if($state){
            $query->andWhere(['state'=>$state]);
        }
        $query->andFilterWhere(['type'=>$type]);
        $list = $query->orderBy(['id'=>SORT_DESC])
                ->limit($limit)
                ->offset($offset)
                ->asArray()
                ->all();
                
        $result['list'] = $list;
        $result['state_name'] = Withdraw::$listExplain;
        return $result; 
    }
    /**
     *  提现手续费
     *  0 J余额
     *  1 D余额
     */
    public function actionGetFee(){
       
        $fee = $this->modelClass::getCashFee();
        $shuifei = Yii::$app->debris->backendConfig('member_cash_shuifei',true);

        $result['fee'] = $fee;
        $result['shuifei'] = $shuifei;
        return ResultHelper::json(200,'ok',$result);

    }

    public function actionDraw()
    {
        if (Yii::$app->request->post()) {
            $member = Yii::$app->user->identity->member;
            $model = new WithdrawForm();
            $model->attributes = Yii::$app->request->post();
            $model->_member = $member;
            $model->member_id = $member->id;
            if($model->add()){
                return true;
            }else{
                return ResultHelper::json(422,$this->getError($model));
            }
        }
    }

    /**
     * 会员提现
     * 
     * @return [type] [description]
     */
    public function actionCashOut()
    {
    
        if (Yii::$app->request->post()) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $member = Yii::$app->user->identity->member;
                
                $password_pay = Yii::$app->request->post('password');
                if(empty($password_pay)){
                    throw new \Exception("支付密码不能为空");
                }
                if (!$member->validateSecurityPassword($password_pay) ) {
                    throw new \Exception("支付密码不正确");
                }
                $amount = Yii::$app->request->post('amount');
                if ($amount <= 0) {
                    throw new \Exception("提取数量不正确");
                }
                $cash_min_money = Yii::$app->debris->backendConfig('member_cash_min_money');
                if ($amount < $cash_min_money) {
                    throw new \Exception("最低提取数量为".$cash_min_money);
                }
                $pay_img = Yii::$app->request->post('pay_img');
                if (!$pay_img) {
                    throw new \Exception("请提交收款二维码");
                }
                $realname = Yii::$app->request->post('realname');
                if (!$realname) {
                    $realname = '';
                }
                // $address_id = Yii::$app->request->post('address_id');
                // if(empty($address_id)){
                //     throw new \Exception("收货地址不能为空");
                // }
                // $address = Address::find()->where(['id'=>$address_id, 'member_id'=>$member->id])->one();
                // if (!$address) {
                //     throw new \Exception('请选择收货地址', 1);
                // }

                $model = new Withdraw();
                $model->type = 1;
                $model->member_id = $member->id;
                $model->order_no = $model->generateNo();
                $model->state = 0;
                $model->province_id = 0;//$address->province_id;
                $model->city_id = 0;//$address->city_id;
                $model->area_id = 0;//$address->area_id;
                $model->address = '';//$address->address_name . $address->address_details;
                $model->bank_user_name = $realname;//$address->realname;
                $model->mobile = '';//$address->mobile;
                $model->amount = $amount;
                $model->pay_img = $pay_img;
                $model->addCashOrder();
                // $model->addBankCard();
                if (!$model->save()) {
                    throw new \Exception($this->getError($model));
                }

                $num = $model->amount;
               
                $action = 'decrZcb'; // 扣除余额
                $remark = '提现';
                Yii::$app->services->memberCreditsLog->$action(new CreditsLogForm([
                    'member' => $member,
                    'num' => $num,
                    'credit_group' => 'cash',
                    'remark' => $remark,
                ]));
                $transaction->commit();
                $result = $model;
                return ResultHelper::json(200,'提现申请提交成功',$result);
            }catch (\Exception $e) {
                $transaction->rollBack();
                return ResultHelper::json(422,$e->getMessage());
            }
        }
        return ResultHelper::json(422,'传输方式错误');
    }

    public function actionUpdateImg()
    {
        $id = Yii::$app->request->post('id');
        $pay_img = Yii::$app->request->post('pay_img');
        $update = Withdraw::updateAll(['pay_img'=>$pay_img],['id'=>$id, 'pay_img'=>'', 'member_id'=>Yii::$app->user->identity->member_id, 'state'=> Withdraw::STATUS_WAIT]);
        if ($update) {
            return ResultHelper::json(200,'打款凭证提交成功');
        } else {
            return ResultHelper::json(422,'该订单已不需要上传凭证');
        }
    }
}